You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言技术问询:二维数组中字符串与目标字符串的比较

Finding a Client ID in a 2D Array Using strcmp()

Hey folks, let's walk through how this code works for looking up client IDs in your 2D array, plus a few notes to keep it running smoothly.

First, you've got a 2D char array client_ids[100][100] set up to store up to 100 client IDs, each with a maximum length of 99 characters (remember, C strings need that extra \0 terminator at the end).

The Lookup Function Breakdown

Here's your implementation again for reference:

char client_ids[100][100];
int find_client_by_id(char* name) {
    for (int i = 0; i < n; i++) {
        if (strcmp(&client_ids[i], name) == 0) {
            return i;
        }
    }
    return -1;
}

Let's break down what's happening here:

  • The function takes a char* name parameter, which is the client ID string you're searching for.
  • The loop runs from i=0 to i=n-1—just make sure n is the actual number of client IDs you've stored in the array (and that it doesn't exceed 100, or you'll hit array out-of-bounds issues!).
  • The strcmp(&client_ids[i], name) call compares the string in the i-th row of your 2D array to the input name. A quick note: you could also write this as strcmp(client_ids[i], name) since client_ids[i] already points to the start of the i-th string (it's equivalent to &client_ids[i][0]). Both work, but the latter is a bit more readable for most C devs.
  • If a match is found (strcmp returns 0), the function immediately returns the index i of the matching client ID. If the loop finishes without finding a match, it returns -1 to signal that the ID wasn't found.

Key Things to Keep in Mind

  • Validate n: Make sure n is properly defined (either as a global variable you update when adding clients, or better yet, pass it as a parameter to the function—this makes your code more reusable and avoids relying on global state).
  • Null-Terminated Strings: Every client ID stored in client_ids must be a properly null-terminated C string. If you forget the \0, strcmp will keep reading memory beyond the array, leading to undefined behavior.
  • Bounds Checking: Ensure n never goes above 100, since your array only has space for 100 client IDs. Going over will cause buffer overflow issues.

内容的提问来源于stack exchange,提问作者Osama Yousuf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:20